/*
 * Providers.java
 *
 * Created on August 4, 2007, 11:59 PM
 * 
 * Copyright 2008 David D. Emory
 * 
 * This file is part of Five Points. See <http://www.fpdev.org> for
 * additional information regarding the project.
 * 
 * Five Points is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Five Points is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Five Points.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.fpdev.core.transit;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author demory
 */
public class Providers implements Serializable {

  private Map<String, Provider> providers_;

  /** Creates a new instance of Providers */
  public Providers() {
    providers_ = new HashMap<String, Provider>();
  }

  public Iterator<Provider> getIterator() {
    return providers_.values().iterator();
  }

  public Iterator<Provider> getIteratorSortedBySize(Routes routes) {
    List<SortableProvider> sorted = new LinkedList<SortableProvider>();
    Iterator<Provider> providers = getIterator();
    while (providers.hasNext()) {
      Provider p = providers.next();
      sorted.add(new SortableProvider(p, routes.routeCount(p)));
    }
    Collections.sort(sorted);
    Collections.reverse(sorted);
    List<Provider> toReturn = new LinkedList<Provider>();
    Iterator<SortableProvider> sortedIter = sorted.iterator();
    while (sortedIter.hasNext()) {
      toReturn.add(sortedIter.next().getProvider());
    }
    return toReturn.iterator();
  }

  // helper class for above
  private class SortableProvider implements Comparable {

    private Provider p_;
    private int size_;

    public SortableProvider(Provider p, int size) {
      p_ = p;
      size_ = size;
    }

    public Provider getProvider() {
      return p_;
    }

    public int compareTo(Object o) {
      return new Integer(size_).compareTo(new Integer(((SortableProvider) o).size_));
    }
  }

  public int providerCount() {
    return providers_.size();
  }

  public Provider getProvider(String id) {
    return providers_.get(id);
  }

  public void newProvider(String id, String name) {
    providers_.put(id, new Provider(id, name));
  }

  public void readFromFile(String filename) {

  }

  public void writeToFile(String filename) {

  }
}
